package com.tomicalab.mobiletoken.ckca;

import iaik.pkcs.pkcs11.TokenException;
import iaik.pkcs.pkcs11.wrapper.CK_TOKEN_INFO;
import iaik.pkcs.pkcs11.wrapper.PKCS11;
import iaik.pkcs.pkcs11.wrapper.PKCS11Exception;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.security.auth.x500.X500Principal;

import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
import org.bouncycastle.util.encoders.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;

import com.tomicalab.mobiletoken.ckca.utils.CertItem;
import com.tomicalab.mobiletoken.ckca.utils.Constant;
import com.tomicalab.mobiletoken.ckca.utils.CustomProgressDialog;
import com.tomicalab.mobiletoken.ckca.utils.P11Other;
import com.tomicalab.mobiletoken.ckca.utils.StorePreferences;

public class RenewCert extends Activity{
	private EditText etSerial;
	private EditText etCertNumber;
	private EditText etEmail;
	private Spinner spCertName;
	private Spinner spTime;

	private Context context;
	private Resources res;
	private ImageButton btnRenew;
	private CertItem[] allCert = null;
	private X509Certificate selectedCert;
	private String keyId;
	private boolean doInOnCreate = true;
	private boolean isImported = false;

	private static CustomProgressDialog progressDialog;
	private static handler handler;

	private StorePreferences storeStatus;

	public static String WS_NAMESPACE = "urn:RenewServices";
	public static String WSDL_URL = "http://renew.ckca.vn/renew_services?WSDL";
	//private static String WS_METHOD_NAME = "Renew";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_renewcert);
		Log.i(Constant.Debug, "onCreate RenewCert");
		doInOnCreate = false;
		isImported = false;
		context = this;
		res = this.getResources();

		storeStatus = new StorePreferences(context);
		//init value
		try {
			Log.i(Constant.Debug, storeStatus.getStatusRenew());
		} catch(NullPointerException e)	{
			Log.i(Constant.Debug, "Null status renew");
			storeStatus.setStatusRenew("0");
		}

		progressDialog = new CustomProgressDialog(context);
		progressDialog.setCancelable(false);
		handler = new handler();

		etEmail = (EditText) findViewById(R.id.et_renew_email);
		//etEmail.setText("vudp@tomicalab.com");

		etSerial = (EditText) findViewById(R.id.et_renew_serial);
		etSerial.setKeyListener(null);

		etCertNumber = (EditText) findViewById(R.id.et_renew_certserial);
		etCertNumber.setKeyListener(null);

		spCertName = (Spinner) findViewById(R.id.sp_renew_certname);

		btnRenew = (ImageButton) findViewById(R.id.btn_renew_ok);

		spTime = (Spinner) findViewById(R.id.sp_certtime);

		if(P11Other.isTokenPlugned == 0)
		{
			Constant.showMessage(res.getString(R.string.inform_handset_plugout), context, res);
			etSerial.setText("");
		}
		else
		{
			if(P11Other.isLoadlib == 0)
			{
				Constant.showMessage(res.getString(R.string.inform_unblock_notInit), context, res);
				etSerial.setText("");
			}
			else
			{
				progressDialog.setShowInfo(res.getString(R.string.inform_pleasewait));
				handler.sleep(0, Constant.SHOWPROGRESSDIALOG, "", "", "");
				handler.sleep(100, Constant.GETALLCERT, "", "", "");
				//initInfo();
			}
		}

		btnRenew.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(P11Other.isTokenPlugned == 0)
				{
					Constant.showMessage(res.getString(R.string.inform_handset_plugout), context, res);
				}
				else
				{
					if(P11Other.isLoadlib == 0)
					{
						Constant.showMessage(res.getString(R.string.inform_handset_loadLib), context, res);
					}
					else
					{
						if(etEmail.getText().toString().length() == 0)
						{
							Constant.showMessage(res.getString(R.string.inform_renew_email_empty), context, res);
						}
						else
						{
							/*
							progressDialog.setShowInfo(res.getString(R.string.inform_renew_getcert));
					    	handler.sleep(0, Constant.SHOWPROGRESSDIALOG, "", "", "");
					    	handler.sleep(100, Constant.GETCERT, "", "", "");
							 */

							if(storeStatus.getStatusRenew().compareTo("1") == 0)
							{
								progressDialog.setShowInfo(res.getString(R.string.inform_renew_getcert));
								handler.sleep(0, Constant.SHOWPROGRESSDIALOG, "", "", "");
								handler.sleep(100, Constant.GETCERT, "", "", "");
							}
							else
							{
								// set dialog message
								AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
										context);
								alertDialogBuilder
								.setTitle(res.getString(R.string.inform_title))
								.setMessage(res.getString(R.string.inform_renew_ask))
								.setCancelable(false)
								.setNegativeButton(res.getString(R.string.inform_button_CANCEL), 
										new DialogInterface.OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												dialog.dismiss();
											}
										})
								.setPositiveButton(res.getString(R.string.inform_button_OK),
										new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,int id) {
															// get prompts.xml view
															LayoutInflater li = LayoutInflater.from(context);
															final View promptsView = li.inflate(R.layout.promt_password, null);
					
															AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
																	context);
					
															// set prompts.xml to alertdialog builder
															alertDialogBuilder.setView(promptsView);
					
															final EditText userInput = (EditText) promptsView
																	.findViewById(R.id.promt_et);
					
															// set dialog message
															alertDialogBuilder
															.setTitle(res.getString(R.string.inform_title))
															.setCancelable(false)
															.setPositiveButton(res.getString(R.string.inform_button_OK),
																	new DialogInterface.OnClickListener() {
																public void onClick(DialogInterface dialog,int id) {
																	Constant.hideSoftKeyboard(RenewCert.this, promptsView);
																	String passwd = userInput.getText().toString();
																	progressDialog.setShowInfo(res.getString(R.string.inform_renew_doing));
																	handler.sleep(0, Constant.SHOWPROGRESSDIALOG, "", "", "");
																	handler.sleep(100, Constant.RENEW, "", passwd, "");
					
																}
															})
															.setNegativeButton(res.getString(R.string.inform_button_CANCEL),
																	new DialogInterface.OnClickListener() {
																public void onClick(DialogInterface dialog,int id) {
																	dialog.cancel();
																}
															});
					
															// create alert dialog
															AlertDialog alertDialog = alertDialogBuilder.create();
					
															// show it
															alertDialog.show();

									}
								})
								.setNegativeButton(res.getString(R.string.inform_button_CANCEL),
										new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,int id) {
										dialog.dismiss();
									}
								});

								// create alert dialog
								AlertDialog alertDialog = alertDialogBuilder.create();

								// show it
								alertDialog.show();

							}

						}
					}
				}
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i(Constant.Debug, "onResume RenewCert");
		isImported = false;
		if(doInOnCreate == false)
		{
			doInOnCreate = true;
		}
		else
		{
			if(P11Other.isTokenPlugned == 0)
			{
				Constant.showMessage(res.getString(R.string.inform_handset_plugout), context, res);
				etSerial.setText("");
				unInitInfo();
			}
			else
			{
				if(P11Other.isLoadlib == 0)
				{
					Constant.showMessage(res.getString(R.string.inform_unblock_notInit), context, res);
					etSerial.setText("");
					unInitInfo();
				}
				else
				{
					progressDialog.setShowInfo(res.getString(R.string.inform_pleasewait));
					handler.sleep(0, Constant.SHOWPROGRESSDIALOG, "", "", "");
					handler.sleep(100, Constant.GETALLCERT, "", "", "");
					//initInfo();
				}
			}
		}
	}

	private void doGetCert() {
		new Thread() {
			public void run() {
				try {
					String DN = spCertName.getSelectedItem().toString();
					String MST = getMST(DN);
					String certSerial = selectedCert.getSerialNumber().toString(16);
					String tokenSerial = etSerial.getText().toString();
					byte[] tmp_thamdinh = "ostt1_".concat(tokenSerial).getBytes();
					byte[] b_thamDinh = null;
					String str_thamDinh = null;
					try {
						MessageDigest md = MessageDigest.getInstance("MD5");
						md.update(tmp_thamdinh);
						b_thamDinh = md.digest();
						str_thamDinh = P11Other.bytesToHex(b_thamDinh);
					} catch (NoSuchAlgorithmException e) {
						e.printStackTrace();
					}

					SoapObject request = new SoapObject(WS_NAMESPACE, "GetCert");

					PropertyInfo pro = new PropertyInfo();
					pro.setNamespace(WS_NAMESPACE);

					pro.setName("var");
					pro.setType("InfoGetCert");

					SoapObject ob = new SoapObject(WS_NAMESPACE, "InfoGetCert");
					ob.addProperty("MST", MST);
					ob.addProperty("CERTIFICATE_SERIAL", certSerial);
					ob.addProperty("TOKENSERIAL", tokenSerial);
					ob.addProperty("THAM_DINH", str_thamDinh.toLowerCase());

					pro.setValue(ob);

					request.addProperty(pro);

					//request.addProperty("MST", MST);
					SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
					envelope.dotNet = true;
					envelope.setOutputSoapObject(request);

					HttpTransportSE httpTransport = new HttpTransportSE(WSDL_URL);

					httpTransport.debug = true;
					httpTransport.call(WS_NAMESPACE +"#"+ "GetCert", envelope);

					Log.i(Constant.Debug,"HTTP REQUEST:\n" + httpTransport.requestDump);
					Log.i(Constant.Debug, "HTTP RESPONSE:\n" + httpTransport.responseDump);

					handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "", "", "");

					if (envelope.bodyIn instanceof SoapObject) { // SoapObject = SUCCESS
						SoapObject soapObject = (SoapObject) envelope.bodyIn;
						SoapObject root = (SoapObject) soapObject.getProperty(0);
						String certificate = (String) root.getProperty("CERTIFICATE");
						certificate = certificate.replace("-----BEGIN CERTIFICATE-----", "");
						certificate = certificate.replace("-----END CERTIFICATE-----", "");
						Log.i(Constant.Debug, "Cert expected");
						Log.i(Constant.Debug, certificate);

						if(certificate.compareTo("") != 0 || certificate != null)
						{
							//storeStatus.setStatusRenew("0");
							progressDialog.setShowInfo(res.getString(R.string.inform_renew_importcert_process_initconnection));
							handler.sleep(0, Constant.SHOWPROGRESSDIALOG, "", "", "");
							handler.sleep(100, Constant.INITCONECTION, "", "", certificate);
						}
						else
						{
							handler.sleep(100, Constant.SHOWERRINFO, res.getString(R.string.inform_renew_getcert_failed), "", "");
						}
					} else if (envelope.bodyIn instanceof SoapFault) { // SoapFault = FAILURE
						SoapFault soapFault = (SoapFault) envelope.bodyIn;		            
						handler.sleep(100, Constant.SHOWERRINFO, soapFault.getMessage(), "", "");
					}

				} catch(Exception e) {
					e.printStackTrace();
					handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "", "", "");
					handler.sleep(100, Constant.SHOWERRINFO, e.getMessage(), "", "");
				}
			}
		}.start();

	}

	private void doRenew(final String pin)
	{
		new Thread(){
			public void run() {
				int rv = 0;
				try {
					rv = P11Other.loginUser(pin);
				} catch (PKCS11Exception e) {
					e.printStackTrace();
				}

				if(rv == 0)
				{

					try {
						//MST
						String DN = spCertName.getSelectedItem().toString();
						String MST = getMST(DN);
						String Email = etEmail.getText().toString();
						String certSerial = selectedCert.getSerialNumber().toString(16);
						String CertTime = spTime.getSelectedItem().toString().substring(0, 1);
						String tokenSerial = etSerial.getText().toString();
						byte[] tmp_thamdinh = "ostt1_".concat(tokenSerial).getBytes();
						byte[] b_thamDinh = null;
						String str_thamDinh = null;
						try {
							MessageDigest md = MessageDigest.getInstance("MD5");
							md.update(tmp_thamdinh);
							b_thamDinh = md.digest();
							str_thamDinh = P11Other.bytesToHex(b_thamDinh);
						} catch (NoSuchAlgorithmException e) {
							e.printStackTrace();
						}


						//CSR
						long key = P11Other.getHandlePriKey(keyId);
						long session = P11Other.getSessionHandle();
						PKCS11 p11Module = P11Other.getPKCS11Module();

						PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
								new X500Principal(selectedCert.getSubjectDN().toString()), selectedCert.getPublicKey());
						JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA1withRSA");
						ContentSigner signer = csBuilder.build(key, p11Module, session);
						PKCS10CertificationRequest csr = p10Builder.build(signer);
						String _csr = new String(Base64.encode(csr.getEncoded()));
						Log.i(Constant.Debug, "MST: "+MST);
						Log.i(Constant.Debug, "DN: "+selectedCert.getSubjectDN().toString());
						Log.i(Constant.Debug, "Email: "+Email);
						Log.i(Constant.Debug, "CertSerial: "+certSerial);
						Log.i(Constant.Debug, "CertTime: "+CertTime);
						Log.i(Constant.Debug, "TokenSerial: "+tokenSerial);
						Log.i(Constant.Debug, "CSR: "+_csr);
						Log.i(Constant.Debug, "ThamDinh: "+str_thamDinh.toLowerCase());


						SoapObject request = new SoapObject(WS_NAMESPACE, "Giahan");
						PropertyInfo pro = new PropertyInfo();
						pro.setNamespace(WS_NAMESPACE);
						pro.setName("var");
						pro.setType("InfoRegGiahan");

						SoapObject ob = new SoapObject(WS_NAMESPACE, "InfoRegGiahan");
						ob.addProperty("MST", MST);
						ob.addProperty("DN", selectedCert.getSubjectDN().toString());
						ob.addProperty("EMAIL", Email);
						ob.addProperty("CERTIFICATE_SERIAL", certSerial);
						ob.addProperty("THOI_HAN_SU_DUNG", CertTime);
						ob.addProperty("TOKENSERIAL", tokenSerial);
						ob.addProperty("REQUEST_CERT", _csr);
						ob.addProperty("THAM_DINH", str_thamDinh.toLowerCase());

						pro.setValue(ob);

						request.addProperty(pro);

						SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
						envelope.dotNet = true;
						envelope.setOutputSoapObject(request);

						HttpTransportSE httpTransport = new HttpTransportSE(WSDL_URL);

						httpTransport.debug = true;
						httpTransport.call(WS_NAMESPACE +"#"+ "Renew", envelope);

						Log.i(Constant.Debug,"HTTP REQUEST:\n" + httpTransport.requestDump);
						Log.i(Constant.Debug, "HTTP RESPONSE:\n" + httpTransport.responseDump);

						handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "", "", "");
						if (envelope.bodyIn instanceof SoapObject) { // SoapObject = SUCCESS
							SoapObject soapObject = (SoapObject) envelope.bodyIn;
							String response = (String) soapObject.getProperty("return");
							Log.i(Constant.Debug, soapObject.toString());
							if(selectedCert.getSubjectDN().toString().compareTo(response) == 0)
							{
								storeStatus.setStatusRenew("1");
								handler.sleep(100, Constant.SHOWERRINFO, "OK", "", "");
							}
						} else if (envelope.bodyIn instanceof SoapFault) { // SoapFault = FAILURE
							SoapFault soapFault = (SoapFault) envelope.bodyIn;		            
							handler.sleep(100, Constant.SHOWERRINFO, soapFault.getMessage(), "", "");
						}


					} catch (PKCS11Exception e) {
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					} catch (OperatorCreationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (XmlPullParserException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else
				{
					handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "", "", "");
					handler.sleep(100, Constant.SHOWERRINFO, res.getString(R.string.inform_login_fail), "", "");
				}
			}
		}.start();
	}

	private void doImport(final String pin, final String cert) {

		new Thread(){
			public void run() {
				int rv;			
				try {
					rv = P11Other.loginUser(pin);
					if(rv == 0) {
						rv = P11Other.importCertificate(Base64.decode(cert));
						if(rv == 0)
						{
							isImported = true;
							handler.sleep(100, Constant.GETALLCERT, "", "", "");
						}
						else
						{
							handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "", "", "");
							handler.sleep(100, Constant.SHOWERRINFO, res.getString(R.string.inform_renew_importcert_failed), "", "");
						}
					}
					else
					{
						handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "", "", "");
						handler.sleep(100, Constant.SHOWERRINFO, res.getString(R.string.inform_changepin_error2), "", "");
					}
				} catch (PKCS11Exception e) {
					e.printStackTrace();
					handler.sleep(100, Constant.SHOWERRINFO, e.getMessage(), "", "");
				} catch (TokenException e) {
					e.printStackTrace();
					handler.sleep(100, Constant.SHOWERRINFO, e.getMessage(), "", "");
				}
			}
		}.start();
	}

	private void initConnection() {
		new Thread(){
			public void run() {
				boolean rv = P11Other.connectToken();
				handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "", "", "");
				if(rv)
				{
					handler.sleep(100, Constant.VERIFYPIN, "", "", "");
				}
				else
				{
					handler.sleep(100, Constant.SHOWERRINFO, res.getString(R.string.inform_handset_connectfail), "", "");
				}
			}
		}.start();
	}

	private void getAllCert() {
		new Thread() {
			public void run() {
				try {
					allCert = P11Other.getAllCerts();
					handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "", "", "");
					handler.sleep(100, Constant.GETALLCERTCOMPLETE, "", "", "");
				} catch (PKCS11Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	private void verifyPin() {
		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(context);
		final View promptsView = li.inflate(R.layout.promt_password, null);

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				context);

		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);

		final EditText userInput = (EditText) promptsView
				.findViewById(R.id.promt_et);

		// set dialog message
		alertDialogBuilder
		.setTitle(res.getString(R.string.inform_title))
		.setCancelable(false)
		.setPositiveButton(res.getString(R.string.inform_button_OK),
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				Constant.hideSoftKeyboard(RenewCert.this, promptsView);
				String passwd = userInput.getText().toString();
				progressDialog.setShowInfo(res.getString(R.string.inform_renew_importcert_doing));
				handler.sleep(0, Constant.SHOWPROGRESSDIALOG, "", "", "");
				handler.sleep(100, Constant.IMPORTCERT, "", passwd, "");
			}
		})
		.setNegativeButton(res.getString(R.string.inform_button_CANCEL),
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				dialog.cancel();
				handler.sleep(0, Constant.SHOWERRINFO, res.getString(R.string.inform_renew_importcert_cancel), "", "");
			}
		});

		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();

		// show it
		alertDialog.show();
	}

	private void initInfo()
	{
		CK_TOKEN_INFO tokenInfo = P11Other.getTokenInformation();
		String series = new String(tokenInfo.serialNumber);
		etSerial.setText(series);
		//get certs info
		//spinner
		List<String> listTime = new ArrayList<String>();
		listTime.add(res.getString(R.string.renew_time_1y));
		listTime.add(res.getString(R.string.renew_time_2y));
		listTime.add(res.getString(R.string.renew_time_3y));
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, listTime);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spTime.setAdapter(dataAdapter);

		//certs
		ArrayList<CertItem> dummies = new ArrayList<CertItem>();
		ArrayList<String> certName = new ArrayList<String>();
		/*        
		try {
			allCert = P11Other.getAllCerts();
		} catch (PKCS11Exception e) {
			e.printStackTrace();
		}
		 */
		if(allCert.length > 0)
		{
			for(int i=0; i< allCert.length; i++)
			{
				dummies.add(allCert[i]);
				certName.add(allCert[i].getDN());
			}

			ArrayAdapter<String> certAdapter = new ArrayAdapter<String>(context, R.layout.spinner_item, certName);
			certAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spCertName.setAdapter(certAdapter);
		}

		spCertName.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				X509Certificate cert = P11Other.getCerFromByte(allCert[arg2].getValue());
				selectedCert = cert;
				keyId = allCert[arg2].getID();
				String serial = cert.getSerialNumber().toString(16);
				etCertNumber.setText(serial);

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {


			}
		});
		if(isImported)
		{
			storeStatus.setStatusRenew("0");
			Constant.showMessage(res.getString(R.string.inform_renew_importcert_ok), context, res);
		}
	}
	private void unInitInfo()
	{
		etCertNumber.setText("");
		etEmail.setText("");
		//spinner
		List<String> listTime = new ArrayList<String>();
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, listTime);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spTime.setAdapter(dataAdapter);

		//certs
		ArrayList<CertItem> dummies = new ArrayList<CertItem>();
		ArrayList<String> certName = new ArrayList<String>();

		ArrayAdapter<String> certAdapter = new ArrayAdapter<String>(context, R.layout.spinner_item, certName);
		certAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spCertName.setAdapter(certAdapter);

		spCertName.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {


			}
		});
	}


	private String getMST(String CN)
	{
		return CN.substring(CN.indexOf("MST:")+4);
	}

	public class handler extends Handler {
		String pin;
		String certificate;
		/*
		public void sleep(long delayMillis, int msgID, Object obj) {
            this.removeMessages(msgID);
            Message msg = new Message();
            msg.what = msgID;
            msg.obj  = obj;
            sendMessageDelayed(msg, delayMillis);
        }
		 */
		public void sleep(long delayMillis, int msgID, String mess, String Password, String certificate) {
			this.removeMessages(msgID);
			Message msg = new Message();
			msg.what = msgID;
			msg.obj  = mess;
			sendMessageDelayed(msg, delayMillis);
			if(Password.compareTo("") != 0)
				this.pin = Password;
			if(certificate.compareTo("") != 0)
				this.certificate = certificate;
		}

		public void handleMessage(Message msg) {
			switch(msg.what) {
			case Constant.SHOWPROGRESSDIALOG:
				Log.e(Constant.Debug, "SHOWPROGRESSDIALOG");
				progressDialog.show();
				super.handleMessage(msg);
				break;
			case Constant.CLOSEPROGRESSDIALOG:
				progressDialog.dismiss();
				super.handleMessage(msg);
				break;
			case Constant.SHOWERRINFO:
				if (null != msg.obj)
				{
					if(msg.obj.toString().compareTo(res.getString(R.string.inform_handset_connectfail))==0)
					{
						String title, button;
						button = res.getString(R.string.inform_button_OK);
						title = res.getString(R.string.inform_title);
						new Builder(context)
						.setTitle(title)
						.setMessage(msg.obj.toString())
						.setPositiveButton(button, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								finish();
							}
						}).show();
					}
					else if(msg.obj.toString().compareTo("OK") == 0) {
						Constant.showMessage(res.getString(R.string.inform_renew_ok), context, res);
					} else if(msg.obj.toString().compareTo("GETCERTOK") == 0) {
						Constant.showMessage(res.getString(R.string.inform_renew_getcert_ok), context, res);
					} else {
						Constant.showMessage(msg.obj.toString(), context, res);
					}
				}
				super.handleMessage(msg);
				break;
			case Constant.RENEW:
				doRenew(pin);
				super.handleMessage(msg);
				break;
			case Constant.GETCERT:
				doGetCert();
				super.handleMessage(msg);
				break;
			case Constant.INITCONECTION:
				initConnection();
				super.handleMessage(msg);
				break;
			case Constant.VERIFYPIN:
				verifyPin();
				super.handleMessage(msg);
				break;
			case Constant.IMPORTCERT:
				doImport(pin, certificate);
				super.handleMessage(msg);
				break;
			case Constant.GETALLCERT:
				getAllCert();
				super.handleMessage(msg);
				break;
			case Constant.GETALLCERTCOMPLETE:
				initInfo();
				super.handleMessage(msg);
				break;
			}

		}
	}

}
